package com.yykj.prescription.server.service.impl;

import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.prescription.server.model.entity.prescription.PrescriptionNoteType;
import com.yykj.prescription.server.model.repository.prescription.PrescriptionNoteTypeRepository;
import com.yykj.prescription.server.service.PrescriptionNoteTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class PrescriptionNoteTypeServiceImpl implements PrescriptionNoteTypeService {
    @Override
    public List<PrescriptionNoteType> hospitalNoteList(Integer hospitalId) {
        List<PrescriptionNoteType> list = repository.findAllByHospitalIdOrderBySorting(hospitalId);
        if (list == null || list.size() == 0) {
            list = generateDefaultList(hospitalId);
        }
        return list;
    }

    private List<PrescriptionNoteType> generateDefaultList(Integer hospitalId) {
        List<PrescriptionNoteType> list = new ArrayList<>();
        List<String> nameList = Arrays.asList("先煎", "后下", "包煎", "另煎", "烊化", "冲服");
        for (String name : nameList) {
            PrescriptionNoteType type = new PrescriptionNoteType();
            type.setNote(name);
            type.setHospitalId(hospitalId);
            list.add(type);
        }
        list = repository.saveAll(list);
        return list;
    }

    @Override
    public PrescriptionNoteType editHospitalNote(PrescriptionNoteType prescriptionNoteType) {
        if (StringUtils.isEmpty(prescriptionNoteType.getNote())
                || prescriptionNoteType.getHospitalId() == null
                || prescriptionNoteType.getHospitalId() == 0) {
            throw new NormalException(ResultEnums.PARAM_ERROR);
        }
        return repository.save(prescriptionNoteType);
    }

    @Override
    public void deleteHospitalNote(Integer id) {
        PrescriptionNoteType prescriptionNoteType = repository.findById(id).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
        repository.delete(prescriptionNoteType);
    }

    private PrescriptionNoteTypeRepository repository;

    @Autowired
    public void setRepository(PrescriptionNoteTypeRepository repository) {
        this.repository = repository;
    }
}
